<?php
require_once 'common.php';

$authorization_code = urldecode($_REQUEST['code']);
//Util::debug('REQUEST',$_REQUEST);
//Util::debug('authorization_code', $authorization_code);
//Util::debug('encrypted authorization_code', Util::encrypt($authorization_code));
$state = null; 
if (array_key_exists('state', $_REQUEST)) 
        $state = json_decode(urldecode($_REQUEST['state']));

$access_token_url = SFDC_ACCESS_TOKEN_URL . urlencode($authorization_code);

// grab URL and parse it
$json = Util::callout($access_token_url, 'POST');
if (isset($json->data->error) || (isset($state->debug) && $state->debug == 'auth')) {
        unset($_SESSION);
        outputPostMessage(CirrusInsight::ServiceResponse(false, $json));
        exit;
}

// Get the user's details
$id_service = Util::callout($json->data->id, 'GET', $headers=array('Authorization: OAuth '.$json->data->access_token));
if (isset($json->data->error) || (isset($state->debug) && $state->debug == 'id')) {
        unset($_SESSION);
        outputPostMessage(CirrusInsight::ServiceResponse(false, $id_service));
        exit;
}

$_SESSION["access_token"] = $json->data->access_token;
$insightUser = new InsightUser($id_service->data->user_id);
$newUser = (!$insightUser->user_id);
$googleRefreshTokenNotFound = (!$insightUser->google_refresh_token);

$insightUser->username = $id_service->data->username;
$insightUser->email = $id_service->data->email;
$insightUser->display_name = $id_service->data->display_name;
$insightUser->utcOffset = ($id_service->data->utcOffset / 1000 / 60 / 60);
$insightUser->refresh_token = Util::encrypt($json->data->refresh_token);

if ($newUser) {
        $insightUser->user_id = $id_service->data->user_id;
        $insightUser->locale = $id_service->data->locale;
        $insightUser->org_id = $id_service->data->organization_id;
        $insightUser->partner_api = str_replace('{version}', API_VERSION, $id_service->data->urls->partner);
        $insightUser->signup_date = date("Y-m-d");
        $insightUser->trial_exp_date = date("Y-m-d", time() + (TRIAL_PERIOD * 24 * 60 * 60));
        $insightUser->status = 'trial';

        // give salesforce employees free demo licenses
        if (stripos($insightUser->email, 'salesforce.com') !== FALSE) {
                $insightUser->status = 'active';
        }

        $insightUser->license_type = 0;

        $result = $insightUser->insert();

        if (!$result) {
                // This will immediately email ME - not log a case.
                Util::mailCI('Insight User creation failure', array($insightUser, $id_service, $json), false);
                unset($_SESSION);
                outputPostMessage(CirrusInsight::ServiceResponse(false));
                exit;
        }
} else {
        $insightUser->update();
}
//Util::debug('insightUser', $insightUser);
$insightUser->createSession($json->data->access_token);
$_SESSION['user_id'] = $insightUser->user_id;

if($googleRefreshTokenNotFound){
    header( 'Location: googleOAuth.php' ) ;    
}
else {
    header( 'Location: main.php' ) ;
}

?>